/**
 * @class Spark.Field
 * @extends Spark.Component
 * <p>带有input标记的输入类的组件.
 * @author njq.niu@hand-china.com
 * @constructor
 * @param {Object} config 配置对象. 
 */
$S.Field = Ext.extend($S.ViewComponent,{    
    validators: [],
    focusCss:'s_fs',
    requiredCss:'s_rq',
    placeholderCss:'s_et',
    invalidCss:'s_ivd',
    constructor: function(config) {
        config.required = config.required || false;
        $S.Field.superclass.constructor.call(this, config);
//        this.initValue(this.originalValue);
        this.applyPlaceholder();
    },
    initFocusElement : function(){
        this.focusEl = this.el;
    },
    initComponent : function(config){
        $S.Field.superclass.initComponent.call(this, config);
        this.el = this.wrap.child('input[stype=input]'); 
    },
//    initValue : function(v){},
    initStatus : function(){
        this.clearInvalid();
        this.initRequired(this.required);
        this.initMaxLength(this.maxLength);
        $S.Field.superclass.initStatus.call(this);
    },
    initRequired : function(required){
        if(this.crrentRequired == required)return;
        this.clearInvalid();        
        this.crrentRequired = required;
        if(required){
            this.wrap.addClass(this.requiredCss);
        }else{
            this.wrap.removeClass(this.requiredCss);
        }
    },
    initMaxLength : function(ml){
        if(ml) this.el.dom.maxLength=ml;
    },
    initDisabled : function(disabled){
        $S.Field.superclass.initDisabled.call(this,disabled);
        this.el.dom.readOnly = disabled;
    },
    initEvents : function(){
        $S.Field.superclass.initEvents.call(this);
        this.addEvents(
        /**
         * @event change
         * change事件.
         * @param {Spark.Field} field field对象.
         * @param {EventObject} e 键盘事件对象.
         */
        'change',
        /**
         * @event keydown
         * 键盘按下事件.
         * @param {Spark.Field} field field对象.
         * @param {EventObject} e 键盘事件对象.
         */
        'keydown',
        /**
         * @event keyup
         * 键盘抬起事件.
         * @param {Spark.Field} field field对象.
         * @param {EventObject} e 键盘事件对象.
         */
        'keyup',
        /**
         * @event keypress
         * 键盘敲击事件.
         * @param {Spark.Field} field field对象.
         * @param {EventObject} e 键盘事件对象.
         */
        'keypress',
        /**
         * @event enterdown
         * 回车键事件.
         * @param {Spark.Field} field field对象.
         * @param {EventObject} e 键盘事件对象.
         */
        'enterdown');
    },
    processListener: function(ou){
        $S.Field.superclass.processListener.call(this, ou);
        this.el[ou]("change",   this.onChange, this)
               [ou]("keyup",    this.onKeyUp, this)
               [ou]("keydown",  this.onKeyDown, this)
               [ou]("keypress", this.onKeyPress, this)
               [ou]("mouseup",  this.onMouseUp, this);
    },
    destroy : function(){
        $S.Field.superclass.destroy.call(this);
        delete this.el;
    },
    setWidth: function(w){
        this.wrap.setStyle("width",(w-2)+"px");//左右边框为2
        this.el.setStyle("width",(w-7)+"px");//paddingleft + leftborder + rightborder
    },
    setHeight: function(h){
        this.wrap.setStyle("height",(h-2)+"px");//上下边框是2
        this.el.setStyle("height",(h-4)+"px");//上下边框2，上下padding是2
    },
    processKeyDown : function(e){
        var keyCode = e.keyCode;
        if(this.isEditor==true && keyCode == 9) e.stopEvent();
        if(keyCode == 27) {
            e.stopEvent();
        }
    },
    processValue : function(v){
        return v;
    },
    processMaxLength : function(rv){
        if(this.isOverMaxLength(rv)){
            var sb = [];
            for (i = 0,k=0; i < rv.length;i++) {
                var cr = rv.charAt(i);
                var cl = cr.match(/[^\x00-\xff]/g);
                if (cl !=null && cl.length>0) {
                    k=k+$S.defaultChineseLength;
                } else {
                    k=k+1
                }
                if(k<=this.maxLength) {
                    sb[sb.length] = cr
                }else{
                    break;
                }
            }
            return sb.join('');
        }
        return rv;
    },  
    isOverMaxLength : function(str){
        if(!this.maxLength) return false;
        var c = 0;
        for (i = 0; i < str.length; i++) {
            var cr = str.charAt(i);
            var cl = cr.match(/[^\x00-\xff]/g);
            if (cl !=null &&cl.length >0) {
                c=c+$S.defaultChineseLength;
            } else {
                c=c+1;
            }
        }
        return c > this.maxLength;
    },
    setValue : function(v, silent){
        $S.Field.superclass.setValue.call(this,v, silent);
        if(this.placeholder && this.el && v !== undefined && v !== null && v !== ''){
            this.wrap.removeClass(this.placeholderCss);
        }
        this.setRawValue(this.formatValue((v === null || v === undefined ? '' : v)));
        this.applyPlaceholder();
    },
    formatValue : function(v){
        var rder = (this.renderer) ? $S.getFunction(this.renderer) : null;
        return (rder!=null) ? rder.call(window,v) : v;
    },
    getRawValue : function(){
        var v = this.el.getValue(),typecase=this.inputCase;
        if(v === this.placeholder || v === undefined){
            v = '';
        }
        if(this.isDbc(v)){
            v = this.dbc2sbc(v);
        }
        if(typecase){
            if(typecase == 'upper'){
                v = v.toUpperCase();
            }else if(typecase == 'lower') {
                v = v.toLowerCase();
            }
        }
        return v;
    },
    applyPlaceholder : function(){
        if(this.placeholder && this.getRawValue().length < 1){
            this.setRawValue(this.placeholder);
            this.wrap.addClass(this.placeholderCss);
        }
    },
    clearInvalid : function(){
        this.wrap.dom.removeAttribute('data-tooltip');
        this.wrap.dom.removeAttribute('data-tooltip-style');
        this.wrap.removeClass(this.invalidCss);
    },
    markInvalid : function(msg){
        if(!this.record)return;
        var field = this.record.getField(this.binder.name)
        var msg = this.record.valid[this.binder.name] || field.get('tooltip');
        this.wrap.set({
            'data-tooltip':msg,
            'data-tooltip-type':'tip',
            'data-tooltip-style':'valid'
        })
        this.wrap.addClass(this.invalidCss);
    },
    select : function(start, end){
        var v = this.getRawValue();
        if(v.length > 0){
            start = start === undefined ? 0 : start;
            end = end === undefined ? v.length : end;
            var d = this.el.dom;
            if(d.setSelectionRange){  
                d.setSelectionRange(start, end);
            }else if(d.createTextRange){
                var range = d.createTextRange();
                range.moveStart("character", start);
                range.moveEnd("character", end-v.length);
                range.select();
            }
        }
        this.isSelect = true;
    },
    setRawValue : function(v){
        if(this.el.dom.value === (v === null || v === undefined ? '' : v)) return;
        this.el.dom.value = (v === null || v === undefined ? '' : v);
    },
//    通过dataset来reset
//    reset : function(){
//        $S.Field.superclass.reset.call(this);
//        this.clearInvalid();
//        this.applyPlaceholder();
//    },
    clearValue : function(){
        this.setValue('', true);
        this.clearInvalid();
        this.applyPlaceholder();
    },
    /**
     * 是否是全角字符
     * @param {} s
     * @return {}
     */
    isDbc : function(s){
        var dbc = false;
        for(var i=0;i<s.length;i++){
            var c = s.charCodeAt(i);
            if((c>65248)||(c==12288)) {
                dbc = true
                break;
            }
        }
        return dbc;
    },
    /**
     * 全角转半角
     * @param {} str
     * @return {}
     */
    dbc2sbc : function(str){
        var result = '';
        for(var i=0;i<str.length;i++){
            code = str.charCodeAt(i);//获取当前字符的unicode编码
            if (code >= 65281 && code <= 65373) {//在这个unicode编码范围中的是所有的英文字母已及各种字符
                result += String.fromCharCode(str.charCodeAt(i) - 65248);//把全角字符的unicode编码转换为对应半角字符的unicode码                
            } else if (code == 12288){//空格
                result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
            } else {
                result += str.charAt(i);
            }
        }
        return result;
    },
    onChange : function(e){
        this.fireEvent('change', this, e);
    },
    onKeyUp : function(e){
        this.fireEvent('keyup', this, e);
    },
    onKeyDown : function(e){
        this.fireEvent('keydown', this, e);
        this.processKeyDown(e);
    },
    onKeyPress : function(e){
        this.fireEvent('keypress', this, e);
    },
    onFocus : function(e){
        if(!this.isFocused){
            this.startValue = this.getValue();
            if(this.placeholder){
                if(this.el.dom.value == this.placeholder){
                    this.setRawValue('');
                }
                this.wrap.removeClass(this.placeholderCss);
            }
//            this.select();
            this.wrap.addClass(this.focusCss);
            $S.Field.superclass.onFocus.call(this,e);
        }
    },
    onBlur : function(e){
        if(this.isFocused){
            var rv = this.getRawValue();
            rv = this.processMaxLength(rv);
            rv = this.processValue(rv);
            this.setValue(rv);
            this.wrap.removeClass(this.focusCss);
            $S.Field.superclass.onBlur.call(this,e);
        }
    },
    onMouseUp : function(e){
        if(this.isSelect) e.stopEvent();
        this.isSelect = false;
    }
})